import Router from "koa-router";
import { Result } from "@/utils/result";
import { uploadService } from "@/service/upload.service";
import { getAccessUrl, mergeChunk, uploadChunk, uploadFile, verifyFileUpload } from "@/middleware/upload.middleware";

// {
//     fieldname: 'file',
//     originalname: '@-阿莘-03.jpg',
//     encoding: '7bit',
//     mimetype: 'image/jpeg',
//     destination: 'G:\\Demo\\koa-template\\upload\\temp',
//     filename: '@-阿莘-03.jpg_1697826074052.jpg',
//     path: 'G:\\Demo\\koa-template\\upload\\temp\\@-阿莘-03.jpg_1697826074052.jpg',
//     size: 214812
// }
export interface UploadFile {
    fieldname: string;
    originalname: string;
    encoding: string;
    mimetype: string;
    destination: string;
    filename: string;
    path: string;
    size: number;
}

// const chunk = {
//     fieldName: 'chunk',
//     originalFilename: '猫-1.jpg',
//     path: 'C:\\Users\\13966\\AppData\\Local\\Temp\\4Q3CLVQCPISGJE_G0KuLYMlF.jpg',
//     headers: [Object],
//     size: 1048576
//   }
export interface ChunkFile {
    fieldName: string;
    originalFilename: string;
    path: string;
    headers: any;
    size: number; // 字节
}

const uploadRouter = new Router({ prefix: "/api/upload" });

uploadRouter.get("/test", ctx => {
    return Result.ok(ctx, null, "get success");
});

/** 普通文件上传 */
export interface FileFormData {
    file: UploadFile;
    filename: string;
    fileHash: string;
}
uploadRouter.post("/", uploadFile);

/** 分片上传 */

// 后端接口的数据定义
export interface ChunkFormData {
    chunk: ChunkFile;
    fileHash: string;
    chunkHash: string; // 格式：fileHash-chunkIndex，如：aoerxxx-7
    chunkIndex: number;
    filename: string;
}
uploadRouter.post("/chunk", uploadChunk);

/** 合并请求 */
export interface Merge {
    fileHash: string;
    filename: string;
    chunkSize: number; // 分片大小（B）
}

uploadRouter.post("/merge", mergeChunk);

/** 获取文件下载地址 */
uploadRouter.get("/:fileHash", getAccessUrl);

/** 验证文件是否上传 */
export interface Verify {
    fileHash: string;
    chunkSize: number; // byte
}
uploadRouter.post("/verify", verifyFileUpload);

export default uploadRouter;
